package com.cyh.blog.core.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cyh.blog.business.service.SysResourcesService;
import com.cyh.blog.business.service.SysUserService;
import com.cyh.blog.persistence.beans.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysResourcesService sysResourcesService;

    /**
     * 必须在config 中配置shiro aop 才会走这个方法
     * 待完成..
     * 给当前登录的用户授予权限， 防止用户请求非他拥有的权限. 只会执行一次
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        Integer userId = (Integer) SecurityUtils.getSubject().getPrincipal();
//        userId = 1;
//        Map<String, Object> map = new HashMap<>();
//        map.put("userId", userId);
//        List<SysResources> sysResources = sysResourcesService.selectUserResources(map);
        return null;
    }

    /**
     * 身份认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        
        System.out.println(userToken.getUsername());
        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();

        SysUser sysUser = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("username", username));


        if (sysUser == null){
            throw new UnknownAccountException("不存在此用户");
        }
        //...判断是否锁定

        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(
                        sysUser.getId(),
                        sysUser.getPassword(),
                        ByteSource.Util.bytes(username),
                        getName());

        return simpleAuthenticationInfo;
    }
}